package cn.piggy.gateway.core.proxy.jdk;

import cn.piggy.gateway.core.proxy.MyGenericReference;
import cn.piggy.gateway.core.session.GatewaySession;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ObjectProxyFactory {
    private final String uri;
    public ObjectProxyFactory(String uri) {
        this.uri = uri;
    }

    private final Map<String, MyGenericReference> genericReferenceCache = new ConcurrentHashMap<>();

    public MyGenericReference newInstance(GatewaySession gatewaySession) {
        return genericReferenceCache.computeIfAbsent(uri, k -> {
            try {
                ObjectProxy objectProxy = new ObjectProxy(gatewaySession);
                // Proxy
//                Class<?> proxyClass = Proxy.getProxyClass(MyGenericReference.class.getClassLoader(), MyGenericReference.class);
                // InvocationHandler
//                Object object = proxyClass.getConstructor(InvocationHandler.class).newInstance(objectProxy);

                Object object = Proxy.newProxyInstance(objectProxy.getClass().getClassLoader(), new Class[]{MyGenericReference.class}, objectProxy);
                return (MyGenericReference) object;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}
